/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include <iostream>
#include "wav.h"
#include <unistd.h>
#include <math.h>
#include <QAudioOutput>
#include <fcntl.h>

using namespace std;

int main(int argc, char *argv[])
{
    Wav file("/home/zyb/res/ww.wav");

    wav_header * h = file.get_header();

    cout << " >> File Read:" << endl;
    cout << " > Container -> " << h->chunk_id << endl;
    cout << " > Format -> " << h->format << endl;
    cout << " > Audio Format (1 = PCM) -> " << h->audio_format << endl;
    cout << " > Bits Per Sample -> " << h->bits_sample << endl;
    cout << " > Channels -> " << h->channels << endl;
    cout << " > Byte rate -> " << h->byte_rate << endl;
    cout << " > Sample rate -> " << h->sample_rate << endl;
    cout << " >> Reading samples..." << endl;

    QAudioFormat audioFormat;
    audioFormat.setCodec("audio/pcm");
    audioFormat.setByteOrder(QAudioFormat::LittleEndian);
    audioFormat.setSampleRate(h->sample_rate);
    audioFormat.setChannelCount((int) h->channels);
    audioFormat.setSampleSize((int)h->bits_sample);
    audioFormat.setSampleType(QAudioFormat::SignedInt);
    QAudioOutput audio(QAudioDeviceInfo::defaultOutputDevice(), audioFormat );
    QIODevice *device = audio.start();

    unsigned int samples = audio.periodSize();
    size_t sample_len = samples;// * (h->bits_sample / 8) * h->channels;
    // Buffer
    char * buffer = new char[sample_len];

    int chunks = 0;
    bool readFinished = false;
    for(;;) {
        chunks = audio.bytesFree() / samples;
        while(chunks > 0)
        {
            size_t n = fread(buffer, sizeof(char), sample_len, file.stream);
            device->write(buffer, n);
            if( n!= sample_len) {
                readFinished = true;
                break;
            }
            --chunks;
        }
        if(readFinished)
            break;
        usleep(1 *1000);
    }
    while(1) {
        if(audio.bytesFree() == audio.bufferSize())
            break;
    }
    device->close();
    audio.stop();
    delete[] buffer;

    return 0;
    //return a.exec();
}
